/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dbclasses;

import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import javax.swing.JOptionPane;

/**
 * Utility class for opening database connections
 * @author keaneb1
 */
public class Dbconnector {
    private static Connection conn=null;
    
    /**
     * Method to create a new database connection from the details in the properties file
     * @return the connection object
     */
    public static Connection getConnected(){
        Properties props = new Properties();
        InputStream is;
        //check first if the properties file can be read
        try {
            is = new FileInputStream("config/db.properties");
            props.load(is);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Properties file problem! " + ex.getMessage());
        }
        //if there is a properties file, create the connection strings
        if(!props.isEmpty()){
            String dbname = props.getProperty("dbname");
            String driver = props.getProperty("driver");
            String url = props.getProperty("url");
            String username = props.getProperty("username");
            String password = props.getProperty("password");

            //try to create a connection to the database usting the string components from above.
            try {
                Class.forName(driver).newInstance();
                conn = DriverManager.getConnection(url + dbname, username, password);
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
                JOptionPane.showMessageDialog(null, "Dbconnector problem! " + ex.getMessage());
            }
        }
        //return the connection object to the calling method
        return conn;
    }
}
